package com.geek.netty.utils;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.Map;

/**
 * @program geek
 * @description: util
 * @author: chanzhugang
 * @create: 2021/03/31 23:52
 */
public class HttpClientUtils {

    public static CloseableHttpClient client = HttpClients.createDefault();

    /**
     * get
     */
    public static String getAsString(String url) throws IOException {
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = client.execute(httpGet);
        try {
            HttpEntity entity = response.getEntity();
            return EntityUtils.toString(entity, "UTF-8");
        } finally {
            response.close();
        }
    }

    /**
     *  post
     */
    public static String postAsString(String url, String json, Map<String, String> headers) throws IOException {
        HttpPost httpPost = new HttpPost(url);
        for (String key : headers.keySet()) {
            httpPost.setHeader(key, headers.get(key));
        }
        httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json;charset=utf-8");

        StringEntity stringEntity = new StringEntity(json, "UTF-8");
        httpPost.setEntity(stringEntity);
        CloseableHttpResponse response = null;
        try {
            response = client.execute(httpPost);
            return EntityUtils.toString(response.getEntity(), "UTF-8");
        } finally {
            if (null != response) {
                response.close();
            }
        }
    }


    public static void main(String[] args) throws IOException {
        String url = "http://127.0.0.1:8801/";
        String result = HttpClientUtils.getAsString(url);
        System.out.println("url:" + url + "+++++" + result);
    }
}